import React, { useContext, useReducer } from 'react'

//处理的函数
const reducer = (prevstate, actions) => {
  console.log(prevstate, actions)
  let newState = { ...prevstate }
  switch (actions.type) {
    case '+10':
      newState.count += 10
      return newState
    case '+20':
      newState.count += 20
      return newState
    default:
      return prevstate
  }
  //最后一定要把对象抛出去
}
//初始状态值
const intialState = {
  count: 1
}
// export default function App() {
//   //全局状态管理器vuex类似
//   const [state, dispatch] = useReducer(reducer, intialState)
//   return (
//     <div>
//       <button onClick={() => dispatch({
//         type: 'minus'
//       })}>-</button>
//       <span>{state.count}</span>
//       <button onClick={() => dispatch({
//         type: 'add'
//       })}>+</button>
//     </div>
//   )
// }
const GlobalContext = React.createContext()
export default function App() {
  const [state, dispatch] = useReducer(reducer, intialState)
  return (
    <div>
      <GlobalContext.Provider value={
        {
          state, dispatch
        }
      }>
        <div>
          <Child1></Child1>
          <Child2></Child2>
        </div>
      </GlobalContext.Provider>
    </div>
  )
}

function Child1() {
  const { state, dispatch } = useContext(GlobalContext)
  return (
    <div>
      1参数:{state.count}
      <button onClick={() => {
        dispatch({
          type: '+10'
        })
      }}>+10</button>
    </div>
  )
}

function Child2() {
  const { state, dispatch } = useContext(GlobalContext)
  return (
    <div>
      2参数:{state.count}
      <button onClick={() => {
        dispatch({
          type: '+20'
        })
      }}>+20</button>
    </div>
  )
}
